package com.copractice.beans;

import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.copractice.beans.signin.SignInBean;

/**
 * Base bean for all managed beans. 
 * 
 * @author Dmitry Churbanov (dmitry.churbanov@gmail.com)
 * @version 1.0 01/02/2010
 */
public class BaseBean {
    
    private static final Logger LOG = LoggerFactory.getLogger(SignInBean.class);
    
    /**
     * Returns <code>HttpSession</code> associated with current http request.
     *  
     * @param ctx instance of <code>FacesContext</code> associated with current request.
     * 
     * @return <code>HttpSession</code> associated with current http request.
     */
    protected HttpSession getSession(FacesContext ctx) {
        return (HttpSession)ctx.getExternalContext().getSession(false);
    }
    
    /**
     * Returns the <code>Map</code> of request parameters.
     * 
     * @return the <code>Map</code> of request parameters
     */
    protected Map<String, String> getRequestParameterMap() {
        return getFacesContext().getExternalContext().getRequestParameterMap();
    }
    
    /**
     * Returns instance of <code>FacesContext</code> associated with current request. 
     *  
     * @return <code>FacesContext</code> associated with current request.
     */
    protected FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }
    
    /**
     * Sets attribute to the session associated with current http request. 
     * 
     * @param key 
     * @param value
     */
    protected synchronized void setSessionAttribute(String key, Object value) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Set session attribute: key = '{}', value = '{}'", key, value);
        }
        getSession(getFacesContext()).setAttribute(key, value);
    }

    /**
     * Gets attribute from the session associated with current http request.
     * 
     * @param key
     * @return
     */
    protected synchronized Object getSessionAttribute(String key) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Get session attribute: key = '{}', value = '{}'", key, 
                      getSession(getFacesContext()).getAttribute(key));
        }
        return getSession(getFacesContext()).getAttribute(key);
    }    
    
}
